const mongoose = require("mongoose");
// const { default: students } = require("../public/src/pages/students");
const get = async () => {
  const page = {};
  // (curPage = ~~curPage), (eachPage = ~~eachPage);
  const studentsModel = mongoose.model("students");
  // page.total = await studentsModel.count();
  // page.maxPage = Math.ceil(page.total / eachPage);
  // 第 1 页：跳过 0 条数，0 - 9
  // 第 2 页：跳过 10 (curPage - 1) *  eachPage
  // 第 3 也： 20
  // 链式调用
  // 查询操作
  // 跳过多少条
  // 查询多少条
  page.rows = await studentsModel
    .find()
    // .skip((curPage - 1) * eachPage)
    // .limit(eachPage)
    // .sort({
    //     _id: -1,    // 倒叙
    // })
    // .populate("gradleId")  // 填充
    .exec(); // 开始执行
  return page;
};
const add = async (student) => {
  const studentsModel = mongoose.model("students");
  return await studentsModel.create(student);
};
const getById = (_id) => {
  const studentsModel = mongoose.model("students");
  return studentsModel.findOne({ _id });
};
const addImg = async ({ _id, url }) => {
  const student = await getById(_id);
  console.log(student);
  // 往 model 里面添加了 url
  student.imgs.push(url);
  // 将 model 里面的数据同步到数据库
  return student.save();
};

const deleteImg = async ({ _id, url }) => {
  const student = await getById(_id);
  // 往 model 里面添加了 url
  student.imgs.pull(url);
  // 将 model 里面的数据同步到数据库
  return student.save();
};
// 删除学生
const deleteStudent = async (_id) => {
  console.log(_id);
  const student = await getById(_id);
  // 往 model 里面添加了 url
  const studentsModel = mongoose.model("students");
  return studentsModel.remove(student);

  // 将 model 里面的数据同步到数据库
  return student.save();
};

// 查查看图片

module.exports = { get, add, getById, addImg, deleteImg, deleteStudent };
